package com.hengxinguotong.zhihuichengjian.ui.engineering.task;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;

import com.google.gson.Gson;
import com.hengxinguotong.zhihuichengjian.R;
import com.hengxinguotong.zhihuichengjian.adapter.TaskAdapter;
import com.hengxinguotong.zhihuichengjian.bean.Task;
import com.hengxinguotong.zhihuichengjian.bean.TaskListRes;
import com.hengxinguotong.zhihuichengjian.ui.BaseActivity;
import com.hengxinguotong.zhihuichengjian.utils.SPUtil;
import com.hengxinguotong.zhihuichengjian.utils.Utils;
import com.hengxinguotong.zhihuichengjian.widget.font.HXEditTextView;
import com.hengxinguotong.zhihuichengjian.widget.font.HXTextView;
import com.hengxinguotong.zhihuichengjian.widget.pullrefresh.PullToRefreshBase;
import com.hengxinguotong.zhihuichengjian.widget.pullrefresh.PullToRefreshListView;
import com.hengxinguotong.zhihuichengjian.widget.view.SelectGroupPop;
import com.lidroid.xutils.http.RequestParams;

import org.apache.http.entity.StringEntity;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 任务列表
 * Created by liux on 2017/3/27.
 */

public class SearchTaskActivity extends BaseActivity {
    @BindView(R.id.iv_back)
    HXTextView ivBack;
    @BindView(R.id.rl_title)
    RelativeLayout rlTitle;
    @BindView(R.id.search_ll)
    LinearLayout searchLl;
    @BindView(R.id.task_lv)
    PullToRefreshListView taskLv;
    @BindView(R.id.state_select_tv)
    HXTextView stateSelectTv;
    @BindView(R.id.iv_p)
    ImageView ivP;
    @BindView(R.id.et_project)
    HXEditTextView etProject;
    private TaskAdapter taskAdapter;
    private int pageIndex = 1;
    private List<Task> tasks;
    private SelectGroupPop mSelectStatePop;
    private String state;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search_task);
        ButterKnife.bind(this);
        taskLv.setMode(PullToRefreshBase.Mode.BOTH);
        taskLv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(SearchTaskActivity.this, SubmitTaskActivity.class);
                intent.putExtra("task", tasks.get(position - 1));
                startActivity(intent);
            }
        });

        taskLv.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                pageIndex = 1;
                getcTaskInfo(null);
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                getcTaskInfo(null);
            }
        });
        getcTaskInfo(getResources().getString(R.string.loading));
    }

    private void getcTaskInfo(String alert) {
        JSONObject jsonObject = new JSONObject();

        try {
            jsonObject.put("userId", SPUtil.getString(this, "userId"));
            jsonObject.put("pageNum", pageIndex);
            if (!Utils.isEmpty(state)) {
                jsonObject.put("status", state);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        RequestParams params = new RequestParams();
        params.addHeader("Content-type", "application/json");
        try {
            params.setBodyEntity(new StringEntity(jsonObject.toString(), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        Utils.requestData(alert, this, "/taskDistribution/queryList/" + SPUtil.getString(this,"uuid"), params, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {
                if (taskLv.isRefreshing()) {
                    taskLv.onRefreshComplete();
                }
                if (!Utils.isEmpty(json)) {
                    Gson gson = new Gson();
                    TaskListRes taskListRes = gson.fromJson(json, TaskListRes.class);
                    addData(taskListRes.getValue());
                }
            }

            @Override
            public void onFailure(String json) {
                if (taskLv.isRefreshing()) {
                    taskLv.onRefreshComplete();
                }
            }
        });
    }


    private void addData(List<Task> datas) {
        if (pageIndex == 1) {
            if(datas.size()==0){
                showEmptyView(taskLv);
            }else{
                dismissEmptyView();
            }
            tasks = datas;
            taskAdapter = new TaskAdapter(this, tasks);
            taskLv.setAdapter(taskAdapter);
            if (datas.size() == Utils.ONCECOUNT) {
                taskLv.setMode(PullToRefreshBase.Mode.BOTH);
            }
        } else {
            tasks.addAll(datas);
            taskAdapter.notifyDataSetChanged();
        }

        if (datas.size() < Utils.ONCECOUNT) {
            taskLv.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
        }

        if (datas.size() != 0) {
            pageIndex++;
        }
    }

    @OnClick({R.id.iv_back, R.id.state_select_tv})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.state_select_tv:
                showSelectPop();
                break;
        }
    }


    private void showSelectPop() {
        String[] strings = {"待受理", "处理中", "待检查", "检查不通过", "已完成"};

        mSelectStatePop = new SelectGroupPop(this, strings, new SelectGroupPop.OnDirListPopItemClicked() {
            @Override
            public void onPopItemClick(int position, String name) {
                state = position + 1 + "";
                pageIndex=1;
                getcTaskInfo(getResources().getString(R.string.loading));
            }
        });
        mSelectStatePop.setFocusable(true);
        mSelectStatePop.setOutsideTouchable(true);
        mSelectStatePop.setBackgroundDrawable(getResources().getDrawable(R.color.color_transparent));
        mSelectStatePop.update();
        mSelectStatePop.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {

            }
        });
        if (mSelectStatePop.isShowing()) {
            mSelectStatePop.dismiss();
        } else {
            mSelectStatePop.showAsDropDown(searchLl);
        }
    }

}
